<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            top: 300px;
            left: 50%;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: aqua;
        }
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        .header  {
            height: 300px;
            background-color: pink;
        }
        .banner {
            height: 300px;
            background-color: blue;
        }
        .main {
            height: 1000px;
            background-color: green;
        }
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>
<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主题部分</div>
    <script>
        // 1. 获取元素
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // banner.offsetTop 就是被卷去头部的大小 一定要写到滚动的外面
        var bannerTop = banner.offsetTop;
        //  当侧边栏固定定位之后应该变化的数值
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        //  获取 main 主体元素
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 页面滚动事件 scroll
        document.addEventListener('scroll', function() {
            // window.pageYOffset 页面被被卷去的头部
            // console.log(window.pageYOffset);
            if(window.pageYOffset >= bannerTop ) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = '300px';
            }
            // 4. 当页面滚动daomain盒子，就显示 goback 模块
            if(window.pageYOffset >= mainTop ) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }
        })

        // new
        // 3. 当我们点击返回顶部模块，就让窗口滚动的页面的最上方
        goBack.addEventListener('click', function() {
            window.scroll(0,0); // 里面的数值是不加单位 px  
        })
    </script>
</body>
</html>